package org.wanho.sms.dao.impl;

import java.util.Date;
import java.util.List;

import org.wanho.sms.dao.StudentDao;
import org.wanho.sms.entity.Clazz;
import org.wanho.sms.entity.Student;
import org.wanho.sms.mapper.StudentMapper;
import org.wanho.sms.util.JdbcTemplate;
import org.wanho.sms.util.RowMapper;

public class StudentDaoImpl implements StudentDao {

	private JdbcTemplate<Student> jt = new JdbcTemplate<>();
	private RowMapper<Student> rm = new StudentMapper();
	
	
	@Override
	public void insert(Student stu) {
		String sql = new StringBuffer()
			.append(" insert into t_student ")
			.append(" 	(name,age,height,birthday,cid)	")
			.append(" values ")
			.append(" 	(?,?,?,?,?) ")
			.toString();
		jt.update(sql, stu.getName(),stu.getAge(),stu.getHeight(),stu.getBirthday(),stu.getClazz().getId());
	}

	@Override
	public void deleteById(int id) {
		String sql = new StringBuffer()
			.append(" delete from  ")
			.append(" 	t_student ")
			.append(" where ")
			.append(" 	id=? ")
			.toString();
		jt.update(sql, id);
	}

	@Override
	public void update(Student stu) {
		String sql = new StringBuffer()
			.append(" update ")
			.append(" 	t_student ")
			.append(" set ")
			.append(" 	name=?,age=?,height=?,birthday=?,cid=? ")
			.append(" where ")
			.append(" 	id=? ")
			.toString();
		jt.update(sql,stu.getName(),stu.getAge(),stu.getHeight(),stu.getBirthday(),stu.getClazz().getId(),stu.getId());
	}

	@Override
	public List<Student> selectAll() {
		String sql = new StringBuffer()
			.append(" select ")
			.append("	s.id,s.name,s.age,s.height,s.birthday,c.id cid,c.name cname  ")
			.append(" from ")
			.append(" 	t_student s inner join t_class c on s.cid=c.id ")
			.toString();
		return jt.query(sql,rm);
	}

	@Override
	public Student selectById(int id) {
		String sql = new StringBuffer()
			.append(" select ")
			.append("	s.id,s.name,s.age,s.height,s.birthday,c.id cid,c.name cname  ")
			.append(" from ")
			.append(" 	t_student s inner join t_class c on s.cid=c.id ")
			.append(" where ")
			.append(" 	s.id=? ")
			.toString();
		return jt.queryForObject(sql, rm, id);
	}

	@Override
	public Student selectByName(String name) {
		String sql = new StringBuffer()
			.append(" select ")
			.append("	s.id,s.name,s.age,s.height,s.birthday,c.id cid,c.name cname  ")
			.append(" from ")
			.append(" 	t_student s inner join t_class c on s.cid=c.id ")
			.append(" where ")
			.append(" 	s.name=? ")
			.toString();
		return jt.queryForObject(sql, rm, name);
	}

	@Override
	public void updateClazzId(int id, int clazzId) {
		String sql = new StringBuffer()
			.append(" update ")
			.append(" 	t_student ")
			.append(" set ")
			.append(" 	cid=? ")
			.append(" where ")
			.append(" 	id=? ")
			.toString();
		jt.update(sql, clazzId, id);
		
	}

}
